<?php

namespace app\api\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\exception\DbException;
use think\Model;

class Sender extends Model
{
    protected $table = 'jxc_sander';
    protected $autoWriteTimestamp = true;
    protected $auto = ['is_default' => 0];
    protected $type = ['address' => 'json'];
    protected $searchField = ['name', 'phone'];

    public function searchNameAttr(Query $query, $value, $data)
    {
        $query->whereLike('name', '%' . $value . '%');
    }

    public function searchPhoneAttr(Query $query, $value, $data)
    {
        $query->where('phone', '=', $value);
    }


    /**
     * @param $data
     * @param int $page
     * @param int $size
     * @return string|\think\Paginator
     */
    public function index($data, $page = 1, $size = 10)
    {
        try {
            $data = array_filter($data);
            if (!empty($data)) {
                return $this->withSearch(array_keys($data), $data)->page($page, $size)->paginate($size);
            } else {
                return $this->page($page, $size)->paginate($size);
            }
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param mixed $id
     * @return array|mixed|\PDOStatement|string|Model
     */
    public function show($id)
    {
        try {
            return $this->findOrFail($id);
        } catch (DataNotFoundException $e) {
            return $e->getMessage();
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $id
     * @param $data
     * @return bool
     */
    public function edit($id, $data)
    {
        try {
            return $this->findOrFail($id)->save($data);
        } catch (DataNotFoundException $e) {
            return $e->getMessage();
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $id
     * @return bool|string
     */
    public function del($id)
    {
        try {
            return $this->findOrFail($id)->delete();
        } catch (DataNotFoundException $e) {
            return $e->getMessage();
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        } catch (DbException $e) {
            return $e->getMessage();
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $data
     * @return bool
     */
    public function store($data)
    {
        return $this->save($data);
    }

}